package com.sunshine.lnuplus.view.Timetable;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.ViewModel;

import com.sunshine.lnuplus.utils.DatabaseHelper;
import com.sunshine.lnuplus.utils.TimeHelper;
import com.sunshine.lnuplus.view.Main.MainActivity;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class TimetableViewModel extends AndroidViewModel {

    private SharedPreferences timetableSetting,weather;
    private int weeksCount;

    public TimetableViewModel(@NonNull Application application) {
        super(application);
        timetableSetting = application.getApplicationContext().getSharedPreferences("timetable_setting",MODE_PRIVATE);
        weather = application.getApplicationContext().getSharedPreferences("weather",MODE_PRIVATE);
        weeksCount = timetableSetting.getInt("weeks_count",16);
    }

    public List<List<String>> getTimetableFromDB() {
        SQLiteDatabase database;
        List<List<String>> lists = new ArrayList<>();
        database = DatabaseHelper.getDatabase(getApplication(),"timetable.db");
        Cursor cursor = database.query("timetable",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            do {
                List<String> list = new ArrayList<>();
                list.add(cursor.getString(cursor.getColumnIndex("cname")));
                list.add(cursor.getString(cursor.getColumnIndex("teacher")));
                list.add(cursor.getString(cursor.getColumnIndex("room")));
                list.add(cursor.getString(cursor.getColumnIndex("time")));
                list.add(cursor.getString(cursor.getColumnIndex("color")));
                list.add(cursor.getString(cursor.getColumnIndex("weeks")));
                lists.add(list);
            }
            while (cursor.moveToNext());
        }
        cursor.close();
        return lists;
    }

    public int getThisWeek(){
        int month,thisWeek;
        if(TimeHelper.getMonth()>8) month = timetableSetting.getInt("begin_date_month",8);
        else month = timetableSetting.getInt("begin_date_month",2);
        thisWeek = TimeHelper.getThisWeek(month,timetableSetting.getInt("begin_date_day",1));
        if(thisWeek>weeksCount) thisWeek = weeksCount;
        return thisWeek;
    }

    public int getWeeksCount(){
        return weeksCount;
    }

    public String getWeather(){
        return weather.getString("city","")+" "+weather.getString("wea",null)+" "+weather.getInt("tem",0)+"℃";
    }

}
